/*
 * Copyright (C) 2011-present ShenZhen iBOXCHAIN Information Technology Co.,Ltd.
 *
 * All right reserved.
 *
 * This software is the confidential and proprietary
 * information of iBOXCHAIN Company of China.
 * ("Confidential Information"). You shall not disclose
 * such Confidential Information and shall use it only
 * in accordance with the terms of the contract agreement
 * you entered into with iBOXCHAIN inc.
 */
package com.example.wac.shiro.filter;

import cn.hutool.json.JSONUtil;
import com.example.wac.dto.BaseResponse;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * @author wuancheng
 * @description
 * @date 2023-04-14 18:23:00
 */

public class RestFormAuthenticationFilter extends FormAuthenticationFilter {
    private static final Logger log = LoggerFactory.getLogger(RestFormAuthenticationFilter.class);

    public RestFormAuthenticationFilter() {
    }

    @Override
    protected boolean pathsMatch(String path, ServletRequest request) {
        String requestURI = this.getPathWithinApplication(request);
        String[] strings = path.split("@@");
        if (strings.length <= 1) {
            return this.pathsMatch(strings[0], requestURI);
        } else {
            String httpMethod = WebUtils.toHttp(request).getMethod();
            return httpMethod.equalsIgnoreCase(strings[1]) && this.pathsMatch(strings[0], requestURI);
        }
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (this.isLoginRequest(request, response)) {
            if (this.isLoginSubmission(request, response)) {
                if (log.isTraceEnabled()) {
                    log.trace("Login submission detected.  Attempting to execute login.");
                }

                return this.executeLogin(request, response);
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("Login page view.");
                }

                return true;
            }
        } else {
            if (log.isTraceEnabled()) {
                log.trace("Attempting to access a path which requires authentication.  Forwarding to the Authentication url [" + this.getLoginUrl() + "]");
            }

            BaseResponse<Object> baseResponse = new BaseResponse<>(BaseResponse.RESULT_CODE_FAIL, "401", "用户未登录");
            flushMsgStrToClient(response, baseResponse);
            return false;
        }
    }

    private static void flushMsgStrToClient(ServletResponse response, Object object) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSONUtil.toJsonStr(object));
        response.getWriter().flush();
    }
}

